package acm.pta14;

import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class TreeBuilder {
    int[] postorder;
    int[] inorder;
    HashMap<Integer, Integer> inorderMap = new HashMap<>();
    int postIdx;

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.postorder = postorder;
        this.inorder = inorder;
        postIdx = postorder.length - 1;

        int idx = 0;
        for (Integer val : inorder)
            inorderMap.put(val, idx++);
        return build(0, inorder.length - 1);
    }

    private TreeNode build(int inLeft, int inRight) {
        if (inLeft > inRight)
            return null;

        int rootVal = postorder[postIdx--];
        TreeNode root = new TreeNode(rootVal);

        int index = inorderMap.get(rootVal);    // 中序的root位置

        root.right = build(index + 1, inRight);
        root.left = build(inLeft, index - 1);
        return root;
    }
}

public class Main {
    public static void main(String[] args) {
        // Assume the input is given as two arrays
        int[] inorder = {6,8,7,4,5,1,3,2};
        int[] postorder = {8,5,4,7,6,3,2,1};

        TreeBuilder builder = new TreeBuilder();
        TreeNode root = builder.buildTree(inorder, postorder);
        inOrder(root);
        System.out.println();
        postOrder(root);
        System.out.println();
        // Print the first and last node of each level
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            System.out.println("First: " + level.get(0) + ", Last: " + level.get(level.size() - 1));
        }
    }

    public static void postOrder(TreeNode root) {
        if (root == null) return;
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }
    public static void inOrder(TreeNode root) {
        if (root == null) return;
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }
}
